package com.gec.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gec.common.BaseContext;
import com.gec.common.R;
import com.gec.entity.ShoppingCart;
import com.gec.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *   购物车
 * </p>
 *
 * @author : [chenxys]
 * @version : [v1.0]
 * @createTime : [2022/7/15 20:15]
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询当前用户所拥有的购物车
     * @author chenxys
     * @return com.gec.common.R<java.util.List<com.gec.entity.ShoppingCart>>
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list(){
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 构造查询条件
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        // 排序
        shoppingCartLambdaQueryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(shoppingCartLambdaQueryWrapper);
        return R.success(shoppingCartList);
    }

    /**
     * 添加商品到购物车
     * @author chenxys
     * @param shoppingCart 商品信息
     * @return com.gec.common.R<com.gec.entity.ShoppingCart>
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart addShoppings = shoppingCartService.add(shoppingCart);
        if (!ObjectUtils.isEmpty(addShoppings)){
            return R.success(addShoppings);
        }
        return R.error("添加失败");
    }

    /**
     * 清空购物车
     * @author chenxys
     * @return com.gec.common.R<java.lang.String>
     */
    @DeleteMapping("/clean")
    public R<String> clean(){
        shoppingCartService.clear();
        return R.success("清空购物车成功");
    }

    /**
     * 减少菜品
     * @author chenxys
     * @param shoppingCart 菜品信息
     * @return com.gec.common.R<com.gec.entity.ShoppingCart>
     */
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart){
        shoppingCartService.sub(shoppingCart);
        return R.success("减少该商品");
    }
}
